<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;

use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;
use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

/**
 * Class ManyiController
 * @package Pay\Controller
 * 众合
 */
class ZhongheController extends PayController{
    protected $config;
    protected $class;
    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));
    }

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);

        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $product = Product::getInstance()->getById(I("request.pay_bankcode",0,"intval"));

        if(!$product){
            $this->showmessage('未找到支付产品!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        $isMobile = isMobile();

        $return = $this->orderadd( $parameter );

        $data = array();
        $data['mch_id'] = $this->config['mch_id'];
        $data['nonce_str'] = md5(time().mt_rand(10000,99999));
        $data['body'] = 'zf';
        $data['detail'] = 'zf';
        $data['out_trade_no'] = $return['orderid'];
        $data['total_fee'] = $return['amount']*100;
        $data['fee_type'] = 'CNY';
        $data['spbill_create_ip'] = getIP();
        $data['notify_url'] = $return['notifyurl'];

        switch($this->config['paytype']) {
            //微信
            case 1:
                $data['trade_type'] = 'trade.weixin.native';
                break;
            //支付宝
            case 3:
                $data['trade_type'] = 'trade.alipay.native';
                break;
            //支付宝H5
            case 4:
                $data['trade_type'] = 'trade.alipay.native';
                break;
            case 6:
                $data['return_url'] = $return['callbackurl'];
                $data['accountType'] = '1';
                $data['cardType'] = '2';
                $data['trade_type'] = 'trade.gateway.pay';

                switch($product['code']){
                    //北京银行
                    case 'BOB':
                        $data['bankType'] = '9014';
                        break;
                    //东亚银行
                    case 'BEA':
                        $data['bankType'] = '8004';
                        break;
                    //中国工商银行
                    case 'ICBC':
                        $data['bankType'] = '9040';
                        break;
                    //光大银行
                    case 'CEB':
                        $data['bankType'] = '9002';
                        break;
                    //广发银行
                    case 'CGB':
                        $data['bankType'] = '9012';
                        break;
                    //华夏银行
                    case 'HXB':
                        $data['bankType'] = '9003';
                        break;
                    //中国建设银行
                    case 'CCB':
                        $data['bankType'] = '9008';
                        break;
                    //交通银行
                    case 'BOCOM':
                        $data['bankType'] = '9005';
                        break;
                    //中国民生银行
                    case 'CMBC':
                        $data['bankType'] = '9010';
                        break;
                    //南京银行
                    case 'NJCB':
                        $data['bankType'] = '9018';
                        break;
                    //宁波银行
                    case 'NBCB':
                        $data['bankType'] = '9024';
                        break;
                    //中国农业银行
                    case 'ABC':
                        $data['bankType'] = '9132';
                        break;
                    //平安银行
                    case 'PAB':
                        $data['bankType'] = '1011';
                        break;
                    //上海银行
                    case 'SHB':
                        $data['bankType'] = '9013';
                        break;
                    //上海浦东发展银行
                    case 'SPDB':
                        $data['bankType'] = '8001';
                        break;
                    //深圳发展银行
                    case 'SDB':
                        $data['bankType'] = '8002';
                        break;
                    //兴业银行
                    case 'CIB':
                        $data['bankType'] = '9015';
                        break;
                    //中国邮政储蓄银行
                    case 'PSBS':
                        $data['bankType'] = '9006';
                        break;
                    //招商银行
                    case 'CMB':
                        $data['bankType'] = '9004';
                        break;
                    //浙商银行
                    case 'CZB':
                        $data['bankType'] = '9093';
                        break;
                    //中国银行
                    case 'BOC':
                        $data['bankType'] = '9021';
                        break;
                    //中信银行
                    case 'CTTIC':
                        $data['bankType'] = '9001';
                        break;
                    default:
                        $this->showmessage('暂不支持此银行卡!',['code'=>C("THIRDCODES.".$this->class)]);
                }
                break;
            default:
                $this->showmessage('暂不支持此支付方式!',['code'=>C("THIRDCODES.".$this->class)]);
        }
        $data['sign'] = $this->getSign($data);

        $xml = arrayToXml($data);
        $res = curl($this->config['gateway'], $xml);
        $res = xmlToArray($res);

        $code = $res['code_url'];

        //file_put_contents("a.txt",var_export($res, true));exit;

        if(in_array($this->config['paytype'],[5,6])){
            echo $code; exit;
        }
		
		//echo '<pre/>'; print_r($res); exit;

        if(!$code){
            if($res['return_msg']){
                $this->showmessage($res['return_msg'],['code'=>C("THIRDCODES.".$this->class)]);
            }
			
			if($res['err_code_des']){
				$this->showmessage($res['err_code_des'],['code'=>C("THIRDCODES.".$this->class)]);
			}

            $this->showmessage('未获取到支付链接!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        header("Location: {$code}");
    }

    private function getSign($data){
        $r = [];
        foreach($data as $k=>$v){
            if($k !== 'sign' && $k !== ''){
                $r[$k] = $v;
            }
        }

        ksort($r);
        $str = httpstr($r) . "&key=".$this->config['signkey'];

        return strtoupper(md5($str));
    }

    //通知
    public function notifyurl(){
        //file_put_contents("a.txt",var_export($_POST,true)."\r\n\r\n");
        //file_put_contents("a.txt",var_export($_GET,true)."\r\n\r\n", FILE_APPEND);
        //file_put_contents("a.txt", file_get_contents('php://input')."\r\n\r\n", FILE_APPEND);
        //file_put_contents("a.txt", date("Y-m-d H:i:s",time())."\r\n\r\n", FILE_APPEND);

		$this->debug_callback();
        $p = $origin = file_get_contents('php://input');

        //$p = "<xml><trade_type><![CDATA[trade.alipay.native]]></trade_type><total_fee><![CDATA[1000]]></total_fee><cash_fee><![CDATA[999]]></cash_fee><transaction_id><![CDATA[M800000202018121811341094603]]></transaction_id><third_trans_id><![CDATA[442]]></third_trans_id><out_trade_no><![CDATA[2018121811341094603]]></out_trade_no><time_end><![CDATA[20181218113253]]></time_end><mch_id><![CDATA[M80000020]]></mch_id><result_code><![CDATA[SUCCESS]]></result_code><return_code><![CDATA[SUCCESS]]></return_code><nonce_str><![CDATA[P4WWlb61yuEQBgab]]></nonce_str><sign><![CDATA[576279B216A4829506BFF377B46A127B]]></sign></xml>";

        $p = xmlToArray($p);

        if(!$p || empty($p)){
            exit("wrong");
        }

        /*
         * Array
        (
            [trade_type] => trade.alipay.native
            [total_fee] => 1000
            [cash_fee] => 999
            [transaction_id] => M800000202018121811341094603
            [third_trans_id] => 442
            [out_trade_no] => 2018121811341094603
            [time_end] => 20181218113253
            [mch_id] => M80000020
            [result_code] => SUCCESS
            [return_code] => SUCCESS
            [nonce_str] => P4WWlb61yuEQBgab
            [sign] => 576279B216A4829506BFF377B46A127B
        )
         */

        //获取订单信息
        $orderid = $p['out_trade_no'];
        $find = M("Order")->where(array("pay_orderid"=>$orderid))->find();
        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据
        M("Order")->where(array("pay_orderid"=>$orderid))->save(array(
            "server_return"=> $origin,
            "pay_orderid_rd"=>$p['transaction_id']
        ));

        switch($p['trade_type']){
            case 'trade.alipay.native':
            case 'trade.weixin.native':
                $this->config = M("Channel")->where(['code'=>$this->class,'paytype'=>3])->find();
                break;
            default:
                $this->config = M("Channel")->where(['code'=>$this->class,'paytype'=>6])->find();
        }
        //获取渠道信息

        $sign = $p['sign'];
        $sign2 = $this->getSign($p);

        if($sign !== $sign2){
            exit("sign_wrong");
        }

        if($p['result_code'] !== 'SUCCESS' || $p['return_code'] !== 'SUCCESS'){
            exit("pay_fail");
        }

        $this->async($find['pay_orderid'],'SUCCESS');
    }

    public function callBackUrl(){

        echo '处理成功'; exit;
    }
}